package com.ztewatch.wearcontacts;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Groups;

import com.ztewatch.wearcontacts.data.IConfigLoader;
import com.ztewatch.wearcontacts.data.SortItem;
import com.ztewatch.wearcontacts.loader.GroupListLoaderUtil;
import com.ztewatch.wearcontacts.loader.SortContactsAndGroupLoader;
import com.ztewatch.wearcontacts.presenter.LoadCursorDataPresenter;
import com.ztewatch.wearcontacts.view.DragGridView;
import com.ztewatch.wearcontacts.view.DragGridView.OnChanageListener;
import com.ztewatch.wearcontacts.view.ILoadCursorDataView;
import com.ztewatch.wearcontacts.view.SortGridViewAdapter;

public class WearContactSortActivity extends Activity implements
		ILoadCursorDataView, IConfigLoader {
//	private ScrollGridView base_edit_gridview;
//	private List<HashMap<String, Object>> baseDataList = new ArrayList<HashMap<String, Object>>();
	private List<SortItem> dataSourceList = new ArrayList<SortItem>();
	private DragGridView contact_sort_gridview;
	private SortGridViewAdapter mSortGridViewAdapter;
	private LoadCursorDataPresenter mLoadCursorDataPresenter;
//	private static final int START_PROGRESS = 0x123;
//	private static final int STOP_PROGRESS = 0x124;
//	private AlertDialog mProgressDialog;
//	private boolean is_first_come_in = false;
//	private Handler mHandler = new Handler() {
//		public void handleMessage(android.os.Message msg) {
//			switch (msg.what) {
//			case START_PROGRESS:
//				mProgressDialog.show();
//				break;
//			case STOP_PROGRESS:
//				mProgressDialog.dismiss();
//				break;
//			default:
//				break;
//			}
//		};
//	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wear_contact_sort);
//		is_first_come_in = true;
		initContactGridView();
//		initProgressDialog();
//		if (!mProgressDialog.isShowing()) {
//			mHandler.sendEmptyMessage(START_PROGRESS);
//		}
//		initBaseGridView();
		mLoadCursorDataPresenter = new LoadCursorDataPresenter(this, this, this);
	}

//	private void initProgressDialog() {
//		AlertDialog.Builder builder = new Builder(this);
//		View v = getLayoutInflater()
//				.inflate(R.layout.dialog_message_view, null);
//		TextView msg = (TextView) v.findViewById(R.id.dialog_message_title);
//		msg.setText("init sort...");
//		builder.setView(v);
//		mProgressDialog = builder.create();
//	}

	private void initContactGridView() {
		boolean isVoiceCall = getIntent().getBooleanExtra(
				WearContactVoiceCallMainActivity.VOICE_CALL_FLAG, false);
		contact_sort_gridview = (DragGridView) findViewById(R.id.contact_sort_gridview);
		mSortGridViewAdapter = new SortGridViewAdapter(this, dataSourceList);
		mSortGridViewAdapter.setVoiceCallFlag(isVoiceCall);
		contact_sort_gridview.setAdapter(mSortGridViewAdapter);
		contact_sort_gridview.setOnChangeListener(new OnChanageListener() {

			@Override
			public void onChange(int from, int to) {
				if (from == 0 || to == 0) {// history
					mLoadCursorDataPresenter.restartLoader(0);
					return;
				} else if (from < 0 || to < 0) {
					return;
				}
				SortItem temp = dataSourceList.get(from);
				if (from < to) {
					for (int i = from; i < to; i++) {
						Collections.swap(dataSourceList, i, i + 1);
					}
				} else if (from > to) {
					for (int i = from; i > to; i--) {
						Collections.swap(dataSourceList, i, i - 1);
					}
				}
				dataSourceList.set(to, temp);
				mSortGridViewAdapter.notifyDataSetChanged();
			}

			@Override
			public void onDragFinish(int form, int to) {
				if (form == 0 || to == 0) {// history
					return;
				}
				saveSortToDatabase(form, to);
			}
		});
	}

	private void saveSortToDatabase(int from, int to) {
		ArrayList<ContentProviderOperation> contact_operations = new ArrayList<ContentProviderOperation>();
		setReflowedPinningOperations(from, to, contact_operations);

		if (!contact_operations.isEmpty()) {
			// update the database here with the new pinned positions
			try {
				getContentResolver().applyBatch(ContactsContract.AUTHORITY,
						contact_operations);
			} catch (RemoteException | OperationApplicationException e) {
			}
		}
	}

	private void setReflowedPinningOperations(int oldPos, int newPinPos,
			ArrayList<ContentProviderOperation> contact_operations) {
		if (oldPos < 0 || newPinPos < 0) {
			return;
		}
		final int lowerBound = Math.min(oldPos, newPinPos);
		final int upperBound = Math.max(oldPos, newPinPos);
		for (int i = lowerBound; i <= upperBound; i++) {
			final SortItem entry = dataSourceList.get(i);

//			final int databasePinnedPosition = i + 1;
			final int databasePinnedPosition = dataSourceList.size() + 1 - i;

			if (entry.getIs_group() == 0) {// contact
				if (entry.getPinned() == databasePinnedPosition)
					continue;
				final Uri uri = Uri.withAppendedPath(Contacts.CONTENT_URI,
						String.valueOf(entry.getContact_id()));
				final ContentValues values = new ContentValues();
				values.put(Contacts.PINNED, databasePinnedPosition);
				contact_operations.add(ContentProviderOperation.newUpdate(uri)
						.withValues(values).build());
				entry.setPinned(databasePinnedPosition);
			} else {// group
				if (entry.getSort_number() == databasePinnedPosition)
					continue;
				final Uri uri = ContentUris.withAppendedId(Groups.CONTENT_URI,
						entry.getGroup_id());
				final ContentValues values = new ContentValues();
				// values.put(Groups.SOURCE_ID, databasePinnedPosition);
				values.put(GroupListLoaderUtil.GROUP_SORT_NUM,
						databasePinnedPosition);
				contact_operations.add(ContentProviderOperation.newUpdate(uri)
						.withValues(values).build());
				entry.setSort_number(databasePinnedPosition);
			}
		}
	}


	@Override
	protected void onStart() {
		super.onStart();
		mLoadCursorDataPresenter.initLoader(0);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mLoadCursorDataPresenter.destroyLoader(0);
	}

	private void fillSortListItem(Cursor c) {
		int contact_id_index;
		int name_index;
		// int pinned_index;
		int photoId_index;
		int group_id_index;
		// int group_title_index;
		int is_group_index;
		// int sourceid_index;
		int sort_no_index;
		int group_photo_index;
		contact_id_index = c.getColumnIndex(Contacts._ID);
		name_index = c.getColumnIndex(Contacts.DISPLAY_NAME_PRIMARY);
		sort_no_index = c.getColumnIndex(SortContactsAndGroupLoader.SORT_NO);
		photoId_index = c.getColumnIndex(Contacts.PHOTO_ID);
		group_id_index = c.getColumnIndex(Groups._ID);
		is_group_index = c.getColumnIndex(SortContactsAndGroupLoader.IS_GROUP);
		group_photo_index = c.getColumnIndex(Contacts.LOOKUP_KEY);
		// sourceid_index = c.getColumnIndex(Groups.SOURCE_ID);
		// group_title_index = c.getColumnIndex(Groups.TITLE);
		SortItem sortItem = new SortItem();
		if (is_group_index != -1) {
			int is_group = c.getInt(is_group_index);
			sortItem.setIs_group(is_group);
			if (is_group == 0) {// contact
				if (contact_id_index != -1) {
					long id = c.getLong(contact_id_index);
					sortItem.setContact_id(id);
				}
				if (name_index != -1) {
					String name = c.getString(name_index);
					sortItem.setName(name);
				}
				if (sort_no_index != -1) {
					long pinned = c.getLong(sort_no_index);
					sortItem.setPinned(pinned);
				}
				if (photoId_index != -1) {
					long photo_id = c.getLong(photoId_index);
					sortItem.setPhotoId(photo_id);
				}
			} else {// group
				if (group_id_index != -1) {
					long id1 = c.getLong(group_id_index);
					sortItem.setGroup_id(id1);
				}
				if (name_index != -1) {
					String title = c.getString(name_index);
					sortItem.setGroup_title(title);
				}
				if (sort_no_index != -1) {
					long sortno = c.getLong(sort_no_index);
					sortItem.setSort_number(sortno);
				}
				if (group_photo_index != -1) {
					byte[] photoarr = c.getBlob(group_photo_index);
					sortItem.setGroup_photo_arr(photoarr);
				}
			}
		}

		dataSourceList.add(sortItem);
	}

	@Override
	public void getLoadFinishCursor(Cursor c) {
		dataSourceList.clear();
		c.moveToPosition(-1);
		while (c.moveToNext()) {
			fillSortListItem(c);
		}
//		if (is_first_come_in) {
//			is_first_come_in = false;
//			if (dataSourceList.size() > 1) {// init sort
//				saveSortToDatabase(dataSourceList.size() - 1, 1);
//			}
//		}
		mSortGridViewAdapter.notifyDataSetChanged();
//		if (mProgressDialog.isShowing()) {
//			mHandler.sendEmptyMessage(STOP_PROGRESS);
//		}
	}

	@Override
	public CursorLoader getConfigLoader() {
		CursorLoader cursorLoader = new SortContactsAndGroupLoader(
				WearContactSortActivity.this);
		Uri uri = LoadCursorDataPresenter.CONTACT_AND_GROUP_AUTHORITY_URI;
		final Uri.Builder builder = uri.buildUpon();
		uri = builder.build();
		cursorLoader.setUri(uri);
		return cursorLoader;
	}
}
